﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;

using Eforcity.Common35;
using Eforcity.Data.Common35;
using Eforcity.EbayApiDb;
using Eforcity.EbayApiDb.DbTypes;
using Eforcity.EbayApi.Ebay.TradingApi.Webservice;

namespace Eforcity.EbayApi
{
    public partial class EbayTradingMdl
    {
        public static long GetEbayApiDailyUsage(EbayApiBaseInputType inputPara)
        {
            EbayTradingApi ebayApi = new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry, inputPara.SessionCallLimit,
                        inputPara.SellerId, inputPara.CredentialsId, false, 10, inputPara.EbayStatConn);
            ApiAccessRuleType[] apiAccessRuleArr = ebayApi.GetApiAccessRules();
            if (apiAccessRuleArr != null)
            {
                foreach (ApiAccessRuleType apiAccessRule in apiAccessRuleArr)
                {
                    if (string.Compare(apiAccessRule.CallName, "ApplicationAggregate", true) == 0 //returns totals for all calls
                        && apiAccessRule.DailyUsageSpecified)
                    {
                        return apiAccessRule.DailyUsage;
                    }
                }
            }
            return -1;
        }

        public static void GetSellerListingByStartDate(GetSellerListingInputType inputPara, BackgroundWorker bw)
        {
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = AppIdEnum.CLS;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);

            List<string> keywordList = EbayListingData.GetKeywordList(inputPara.EbayStatConn);

            //SellerLoop
            foreach (int sellerId in inputPara.SellerIdList)
            {
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;

                        try
                        {
                            EbayTradingApi ebayApi =
                            new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                                inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);

                            //Get Seller Name For Report Progress
                            string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);
                            bool isOwner = EbaySellerData.IsAcctOwner(sellerId, inputPara.EbayStatConn);
                            Dictionary<int, List<string>> filterKeywordDict = null;
                            if (!isOwner)
                            {
                                filterKeywordDict = EbayListingData.GetFilterKeywordDict(inputPara.EbayStatConn);
                            }

                            for (DateTime processDay = inputPara.DateUTCFrom; processDay <= inputPara.DateUTCTo; processDay = processDay.AddDays(1))
                            {
                                #region HourLoop - Loop for HOUR lots, divid a day to 24hr
                                for (int processHrIdx = 0; processHrIdx < 24; processHrIdx += inputPara.ListingHourProcessLot)
                                {
                                    try
                                    {
                                        EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                                        DateTime processStartTimeFrom = processDay.AddHours(processHrIdx);
                                        DateTime processStartTimeTo = processDay.AddHours(processHrIdx + inputPara.ListingHourProcessLot);

                                        if (processStartTimeTo > DateTime.Now.ToUniversalTime().AddMinutes(-30))
                                        {
                                            bw.ReportProgress(0, "The DateTime is not Finished. " + processStartTimeTo);
                                            break;
                                        }
                                        //Check if it this processed
                                        if (!EbayListingData.IsProcessedStartDateTimeSlot(sellerId, processStartTimeFrom, inputPara.EbayStatConn))
                                        //if (true)
                                        {
                                            //Report Progress 
                                            if (bw != null)
                                            {
                                                bw.ReportProgress(0, "Processing [" + sellerName + "]" + FileUtility.NewLine +
                                                    "From(UTC):  " + processStartTimeFrom + FileUtility.NewLine +
                                                    "To(UTC):    " + processStartTimeTo);
                                            }
                                            loopCount++;

                                            //Get the listingItem Result List
                                            List<EbayListingItemType> listingResponseList =
                                                ebayApi.GetSellerList(sellerId, sellerName, isOwner,
                                                processStartTimeFrom.AddMinutes(-1),
                                                processStartTimeTo.AddMinutes(1),
                                                false, inputPara.ListingEntriesPerPage);

                                            //List<EbayListingItemType> listingResponseList =
                                            //    ebayApi.GetSellerList(1273, "la_maison_des_prix_fous", false, ConvertUtility.ToDateTime("2010-10-30 23:59:00"), ConvertUtility.ToDateTime("2010-11-10 1:01:00"), false, 200);

                                            

                                            //It is Possible nothing in response in a specific time and seller
                                            //BUT "Null" Means Error, Must Manual Check
                                            if (listingResponseList != null)
                                            {
                                                //Insert to DB
                                                try
                                                {
                                                    ////Check Title Error-Double Space (Added 07-Nov-2007)
                                                    //foreach (EbayListingItemType ebayItem in listingResponseList)
                                                    //{
                                                    //    if (isOwner && ebayItem.Title.Trim().IndexOf("  ") >= 0)
                                                    //    {
                                                    //        if (!MwData.ExistMwErrorTitle(ebayItem.ItemId, inputPara.EbayStatConn))
                                                    //        {
                                                    //            MwData.InsertMwErrorTitle(ebayItem, inputPara.EbayStatConn);
                                                    //        }
                                                    //        ebayItem.Title = ConvertUtility.Trim(ebayItem.Title.Replace("  ", " "));
                                                    //    }
                                                    //}


                                                    EbayListingData.InsertListingList(listingResponseList, keywordList, filterKeywordDict, isOwner, inputPara.EbayStatConn, inputPara.EbayApiFilterDbConn);

                                                    //update History Table
                                                    EbayListingData.InsertProcessedStartDateTimeSlot(sellerId, processStartTimeFrom, inputPara.EbayStatConn);
                                                    //EbayListingData.UpdateRetryLogListingStartDate(sellerId, processStartTimeFrom, true, inputPara.EbayStatConn);
                                                }
                                                catch (Exception ex)
                                                {
                                                    //Log down the DB errors
                                                    //Retry them later
                                                    //EbayListingData.InsertRetryLogListingStartDate(sellerId, processStartTimeFrom, inputPara.EbayStatConn);
                                                    EbayErrorData.InsertErrorGetSellerList(sellerId, processStartTimeFrom, processStartTimeTo, 0, 0, EbayErrorTypeEnum.SysLevel, -2, ex.Message, inputPara.EbayStatConn);
                                                }
                                            }
                                            else
                                            {
                                                //Logdown the error for later process
                                                //EbayListingData.InsertRetryLogListingStartDate(sellerId, processStartTimeFrom, inputPara.EbayStatConn);

                                                //Check If there is Error in SellerId (changename)
                                                if (!EbaySellerData.IsSellerEnable(sellerId, inputPara.EbayStatConn))
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //Report error
                                        bw.ReportProgress(0, "Error: HourLoop - " + ex.Message);
                                        //By Pass
                                        continue;
                                    }
                                }
                                #endregion
                                if (!EbaySellerData.IsSellerEnable(sellerId, inputPara.EbayStatConn))
                                {
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //Report error
                            bw.ReportProgress(0, "Error: SellerLoop - " + ex.Message);
                            //By Pass
                            //continue;
                        }
                        EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }

            //Report Progress
            bw.ReportProgress(100, "Completed");
        }

        public static void GetSellerListingByEndDate(GetSellerListingInputType inputPara, BackgroundWorker bw)
        {
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = AppIdEnum.CLE;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);

            List<string> keywordList = EbayListingData.GetKeywordList(inputPara.EbayStatConn);

            //SellerLoop
            foreach (int sellerId in inputPara.SellerIdList)
            {
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;

                        try
                        {
                            EbayTradingApi ebayApi =
                            new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                                inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);


                            //Get Seller Name For Report Progress
                            string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);
                            bool isOwner = EbaySellerData.IsAcctOwner(sellerId, inputPara.EbayStatConn);
                            Dictionary<int, List<string>> filterKeywordDict = null;
                            if (!isOwner)
                            {
                                filterKeywordDict = EbayListingData.GetFilterKeywordDict(inputPara.EbayStatConn);
                            }

                            for (DateTime processDay = inputPara.DateUTCFrom; processDay <= inputPara.DateUTCTo; processDay = processDay.AddDays(1))
                            {
                                #region HourLoop - Loop for HOUR lots, divid a day to 24hr
                                for (int processHrIdx = 0; processHrIdx < 24; processHrIdx += inputPara.ListingHourProcessLot)
                                {
                                    try
                                    {
                                        EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                                        DateTime processEndTimeFrom = processDay.AddHours(processHrIdx);
                                        DateTime processEndTimeTo = processDay.AddHours(processHrIdx + inputPara.ListingHourProcessLot);

                                        if (processEndTimeTo > DateTime.Now.ToUniversalTime().AddMinutes(-30))
                                        {
                                            bw.ReportProgress(0, "The DateTime is not Finished. " + processEndTimeTo);
                                            break;
                                        }
                                        //Check if it this processed
                                        if (!EbayListingData.IsProcessedEndDateTimeSlot(sellerId, processEndTimeFrom, inputPara.EbayStatConn))
                                        //if(true)
                                        {
                                            //Report Progress 
                                            if (bw != null)
                                            {
                                                bw.ReportProgress(0, "Processing [" + sellerName + "]" + FileUtility.NewLine +
                                                    "From(UTC):  " + processEndTimeFrom + FileUtility.NewLine +
                                                    "To(UTC):    " + processEndTimeTo);
                                            }
                                            loopCount++;

                                            //Get the listingItem Result List
                                            List<EbayListingItemType> listingResponseList =
                                                ebayApi.GetSellerList(sellerId, sellerName,isOwner,
                                                processEndTimeFrom.AddMinutes(-1),
                                                processEndTimeTo.AddMinutes(1),
                                                true, inputPara.ListingEntriesPerPage);

                                            //It is Possible nothing in response in a specific time and seller
                                            //BUT "Null" Means Error, Must Manual Check
                                            if (listingResponseList != null)
                                            {
                                                //Insert to DB
                                                try
                                                {
                                                    foreach (EbayListingItemType ebayItem in listingResponseList)
                                                    {
                                                        ////Check Title Error-Double Space (Added 07-Nov-2007)
                                                        //if (isOwner && ebayItem.Title.Trim().IndexOf("  ") >= 0)
                                                        //{
                                                        //    if (!MwData.ExistMwErrorTitle(ebayItem.ItemId, inputPara.EbayStatConn))
                                                        //    {
                                                        //        MwData.InsertMwErrorTitle(ebayItem, inputPara.EbayStatConn);
                                                        //    }
                                                        //    ebayItem.Title = ConvertUtility.Trim(ebayItem.Title.Replace("  ", " "));
                                                        //}

                                                        //If Ended, and ListingType NOT 6,7,8,12,13, Set to Completed
                                                        if (!isOwner && ebayItem.ListingStatus == EbayListingStatusEnum.Ended)
                                                        {
                                                            List<int> nonAuctionListingType = new List<int>() { 6, 7, 8, 12, 13 };
                                                            if (!nonAuctionListingType.Contains(ebayItem.ListingType))
                                                            {
                                                                ebayItem.ListingStatus = EbayListingStatusEnum.Completed;
                                                            }
                                                        }
                                                    }


                                                    EbayListingData.InsertListingList(listingResponseList, keywordList, filterKeywordDict, isOwner, inputPara.EbayStatConn, inputPara.EbayApiFilterDbConn);

                                                    //update History Table
                                                    EbayListingData.InsertProcessedEndDateTimeSlot(sellerId, processEndTimeFrom, inputPara.EbayStatConn);
                                                    //EbayListingData.UpdateRetryLogListingEndDate(sellerId, processEndTimeFrom, true, inputPara.EbayStatConn);
                                                }
                                                catch (Exception ex)
                                                {
                                                    //Log down the DB errors
                                                    //Retry them later
                                                    //EbayListingData.InsertRetryLogListingEndDate(sellerId, processEndTimeFrom, inputPara.EbayStatConn);
                                                    EbayErrorData.InsertErrorGetSellerList(sellerId, processEndTimeFrom, processEndTimeTo, 0, 0, EbayErrorTypeEnum.SysLevel, -2, ex.Message, inputPara.EbayStatConn);
                                                }
                                            }
                                            else
                                            {
                                                //Logdown the error for later process
                                                //EbayListingData.InsertRetryLogListingEndDate(sellerId, processEndTimeFrom, inputPara.EbayStatConn);

                                                //Check If there is Error in SellerId (changename)
                                                if (!EbaySellerData.IsSellerEnable(sellerId, inputPara.EbayStatConn))
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //Report error
                                        bw.ReportProgress(0, "Error: HourLoop - " + ex.Message);
                                        //By Pass
                                        continue;
                                    }
                                }
                                #endregion
                                if (!EbaySellerData.IsSellerEnable(sellerId, inputPara.EbayStatConn))
                                {
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //Report error
                            bw.ReportProgress(0, "Error: SellerLoop - " + ex.Message);
                            //By Pass
                            //continue;
                        }
                        EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }

            //Report Progress
            bw.ReportProgress(100, "Completed");
        }

        public static void GetBidders(GetAllBiddersInputType inputPara, BackgroundWorker bw)
        {
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = inputPara.IsGTC ? AppIdEnum.CGB : AppIdEnum.CB;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);

            //SellerLoop
            foreach (int sellerId in inputPara.SellerIdList)
            {
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;

                        try
                        {
                            EbayTradingApi ebayApi =
                            new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                                inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);

                            string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);

                            List<Int64> itemIdList;
                            if (inputPara.IsGTC)
                            {
                                itemIdList = EbayListingData.GetGTCItemIdList(sellerId, inputPara.MaxSoldValue, inputPara.EbayStatConn);
                            }
                            else
                            {
                                itemIdList = EbayListingData.GetEndedItemIdList(sellerId, inputPara.DateFrom, inputPara.DateTo, inputPara.MaxSoldValue, inputPara.EbayStatConn);
                            }

                            //BatchLoop
                            for (int idx = 0; idx < itemIdList.Count; idx += inputPara.BidderProcessLot)
                            {
                                try
                                {
                                    EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                                    int batchSize = inputPara.BidderProcessLot;
                                    if (itemIdList.Count - idx < inputPara.BidderProcessLot)
                                    {
                                        batchSize = itemIdList.Count - idx;
                                    }
                                    List<Int64> batchItemIdList = itemIdList.GetRange(idx, batchSize);

                                    if (bw != null && batchItemIdList.Count > 0)
                                    {
                                        bw.ReportProgress(0, "Processing [" + sellerName + "]: " + (idx + 1) + " - " + (idx + batchSize) + " of " + itemIdList.Count);
                                    }
                                    loopCount++;

                                    List<EbayItemBiddersType> ebayItemBiddersList = ebayApi.GetAllBidders(batchItemIdList, bw);
                                    if (ebayItemBiddersList != null)
                                    {
                                        //InsertLoop
                                        foreach (EbayItemBiddersType ebayItemBidders in ebayItemBiddersList)
                                        {
                                            long itemId = ebayItemBidders.ItemId;
                                            List<EbayBidderType> ebayBidderList = ebayItemBidders.EbayBidderList;
                                            if (itemId > 0 && ebayBidderList != null)
                                            {
                                                try
                                                {
                                                    if (inputPara.IsGTC && EbayListingData.GetGTCItemStatus(itemId, inputPara.EbayStatConn) == (int)EbayListingStatusEnum.GTCRelisted)
                                                    {
                                                        EbayBidderData.InsertGtcBidderList(itemId, ebayBidderList, inputPara.EbayStatConn);
                                                    }
                                                    else
                                                    {
                                                        EbayBidderData.InsertBidderList(itemId, ebayBidderList, inputPara.EbayStatConn);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    //Report error
                                                    bw.ReportProgress(0, "Error: InsertLoop - " + ex.Message);
                                                    //By Pass
                                                    continue;
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //Report error
                                    bw.ReportProgress(0, "Error: BatchLoop - " + ex.Message);
                                    //By Pass
                                    continue;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //Report error
                            bw.ReportProgress(0, "Error: SellerLoop - " + ex.Message);
                            //By Pass
                            //continue;
                        }
                        EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }
        }

        public static int EndItem(EndItemInputType inputPara, BackgroundWorker bw, ref int appError, ref int sysError)
        {
            appError = 0;
            sysError = 0;

            //with the specific account
            EbayTradingApi ebayApi =
                    new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                        inputPara.SessionCallLimit, inputPara.SellerId, false, inputPara.MinCallAvail, inputPara.EbayStatConn);

            int successEndCount = 0;

            //loop the ebayid
            foreach (Int64 eBayItemId in inputPara.CurrentEbayItemIdList)
            {
                //CAll The End Item
                ApiErrorType errorType = ebayApi.EndItem(eBayItemId, inputPara.SellerId, EndReasonCodeType.NotAvailable);

                if (errorType == ApiErrorType.NoError)
                {
                    //if (!EbayEndItemData.ExistProcHistEndItem(eBayItemId, inputPara.EbayStatConn))
                    //{
                        EbayEndItemData.InsertProcHistEndItem(eBayItemId, 0, inputPara.EbayStatConn);
                    //}
                    //else
                    //{
                    //    EbayEndItemData.UpdateProcHistEndItem(eBayItemId, 0, inputPara.EbayStatConn);
                    //}
                    successEndCount++;
                }
                else if (errorType == ApiErrorType.SystemError)
                {
                    EbayEndItemData.InsertProcHistEndItem(eBayItemId, ConvertUtility.ToInt(ApiErrorType.SystemError), inputPara.EbayStatConn);
                    sysError++;
                }
                else if (errorType == ApiErrorType.ApplicationError)
                {
                    EbayEndItemData.InsertProcHistEndItem(eBayItemId, ConvertUtility.ToInt(ApiErrorType.ApplicationError), inputPara.EbayStatConn);
                    appError++;
                }
            }

            return successEndCount;
        }
    }
}
